//
//  HttpBusiManager.m
//  qwm
//
//  Created by kevin on 2023/3/23.
//

#import "HttpBusiManager.h"
#import "Reachability.h"

#define kDefineTokenKey           @"kDefineTokenKey"

@implementation HttpBusiManager
static HttpBusiManager *_sharedInstance = nil;
static dispatch_once_t once_token = 0;
+(instancetype)Instance {
    dispatch_once(&once_token, ^{
        if (_sharedInstance == nil) {
            _sharedInstance = [[super allocWithZone:NULL] init] ;
        }
    });
    return _sharedInstance;
}
#pragma mark -上传文件-头像图片
//-(void)uploadFile:(NSString*)resUrl
//              Dic:(NSDictionary*)resBodyDic
//              Img:(UIImage*) imageData
//          success:(void (^)(JMPHttpResponse *response, NSInteger resStatusCode))success
//          failure:(void (^)(JMPHttpResponse *response, NSInteger resStatusCode,NSError *error))failure
//{
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    //ContentType设置
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"image/jpeg",@"image/png",@"application/octet-stream",@"text/json",nil];
//    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer= [AFHTTPResponseSerializer serializer];
//    //网络请求
//    NSString *url =[NSString stringWithFormat:@"%@%@", QWM_BASE_API_URL, resUrl];//链接
//    //请求体改模型字典{}为null
//    NSString *jsonString =resBodyDic.mj_JSONString;
//    jsonString =[jsonString stringByReplacingOccurrencesOfString:@"{}" withString:@"null"];
//    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//    NSError *err;
//    NSDictionary *reqParamsDic = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                        options:NSJSONReadingMutableContainers
//                                                          error:&err];
//    
//    [manager POST:url parameters:reqParamsDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        
//        //把image  转为data , POST上传只能传data
//        NSData *data = UIImageJPEGRepresentation(imageData,0.5);
//        if (data) {
//            //上传的参数(上传图片，以文件流的格式)
//            [formData appendPartWithFileData:data
//                                        name:@"file"
//                                    fileName:@"gauge.png"
//                                    mimeType:@"image/png"];
//        }
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        //请求成功的block回调
//        [SWHUDUtil hideHudView];
//        
//        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//        
//        JMPHttpResponse *jmpResponse = [[JMPHttpResponse alloc] initWithUrl:url];
//        jmpResponse.reqParams = reqParamsDic;
//        jmpResponse.rspData = dic;
//            
//        NSInteger errorCodeNum = [jmpResponse.rspData[@"code"] integerValue];
//        //NSString *errorMessageStr =jmpResponse.rspData[@"msg"];
//        if (errorCodeNum != 200) {
//            failure(jmpResponse, errorCodeNum,nil);
//        }else
//        {
//            //正常-返回数据
//            success(jmpResponse, errorCodeNum);
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        [SWHUDUtil hideHudView];
//        failure(nil, 0,error);
//    }];
//}



#pragma mark -请求后台操作
-(void)sendRequestHttpDataUrl:(NSString*)resUrl
                          Dic:(NSDictionary*)resBodyDic
                    resMethod:(JMP_HTTP_METHOD)resMethod
                      success:(void (^)(JMPHttpResponse *response, NSInteger resStatusCode,NSString *errorMessage))success
                      failure:(void (^)(JMPHttpResponse *response, NSInteger resStatusCode,NSError *error))failure
{
    [self sendRequestHttpDataUrl:resUrl Dic:resBodyDic resMethod:resMethod isCheckReachability:YES success:success failure:failure];
}
-(void)sendRequestHttpDataUrl:(NSString*)resUrl
                          Dic:(NSDictionary*)resBodyDic
                    resMethod:(JMP_HTTP_METHOD)resMethod
          isCheckReachability:(BOOL)isCheckReachability
                      success:(void (^)(JMPHttpResponse *response, NSInteger resStatusCode,NSString *errorMessage))success
                      failure:(void (^)(JMPHttpResponse *response, NSInteger resStatusCode,NSError *error))failure
{
    //网络判断
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    if (reach.currentReachabilityStatus == NotReachable) {
        if (isCheckReachability){
            UIAlertView *alert =[[UIAlertView alloc]initWithTitle:nil message:@"网络不给力，请检查网络设置。" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alert show];
        }
        [SWHUDUtil hideHudView];
        return;
    }
    
    //网络请求
    NSString *url = [NSString stringWithFormat:@"%@%@", QWM_BASE_API_URL, resUrl];//链接
    JMPHttpRequest *jmpRequest = [[JMPHttpRequest alloc] initWithUrl:url params:@{}];
  
    jmpRequest.method=resMethod;//请求方式
    
    if (!resBodyDic) {
        failure(nil, -100,nil);
        return;
    }
    //请求体改模型字典{}为null
    NSString *jsonString =resBodyDic.mj_JSONString;
    jsonString =[jsonString stringByReplacingOccurrencesOfString:@"{}" withString:@"null"];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    jmpRequest.params =dic;//请求体
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    //请求方式
    NSMutableURLRequest *request = nil;
    if (jmpRequest.method == JMP_HTTP_METHOD_GET) {
        request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:jmpRequest.url parameters:jmpRequest.params error:nil];
    }else if(jmpRequest.method == JMP_HTTP_METHOD_POST) {
        request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:jmpRequest.url parameters:jmpRequest.params error:nil];
    }else if(jmpRequest.method == JMP_HTTP_METHOD_POST_JSON) {
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:jmpRequest.url parameters:jmpRequest.params error:nil];
    }else if(jmpRequest.method == JMP_HTTP_METHOD_PUT_JSON) {
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"PUT" URLString:jmpRequest.url parameters:jmpRequest.params error:nil];
    }else if (jmpRequest.method == JMP_HTTP_METHOD_DELETE_JSON){
        request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"DELETE" URLString:jmpRequest.url parameters:jmpRequest.params error:nil];
    }
    if (!request) {
        [SWHUDUtil hideHudView];
        return;
    }
    
//    [request setValue:[ZBCOMMETH getEquipmentVersion] forHTTPHeaderField:@"x-zbb-version"];//版本号
//    if ([self getToken]) {
//        [request setValue:[self getToken] forHTTPHeaderField:@"x-zbb-token"];
//    }
    
    request.timeoutInterval = jmpRequest.timeoutInterval;//设置超时

    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        
        JMPHttpResponse *jmpResponse = [[JMPHttpResponse alloc] initWithUrl:jmpRequest.url];
        jmpResponse.reqParams = jmpRequest.params;
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        if (!error) {
            jmpResponse.rspData = responseObject;
            NSInteger errorCodeNum = [jmpResponse.rspData[@"code"] integerValue];
            NSString *errorMessageStr =jmpResponse.rspData[@"msg"];
            //正常-返回数据
            success(jmpResponse, errorCodeNum,errorMessageStr);
        }else
        {
            failure(jmpResponse, httpResponse.statusCode,error);
        }
    }];
    [dataTask resume];
}

#pragma mark- 保存token
-(void)saveToken:(NSString *)token
{
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:kDefineTokenKey];
}
-(NSString*)getToken
{
    return [[NSUserDefaults standardUserDefaults] stringForKey:kDefineTokenKey];
}
-(BOOL)hasToken
{
    NSString *token = [self getToken];
    return token.length>0?YES:NO;
}
-(void)clearToken
{
   [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDefineTokenKey];
}
#pragma mark- 校验会员过期时间
//-(void)checkUserVIPTime
//{
//    [self checkUserVIPTime:YES];
//}
//-(void)checkUserVIPTime:(BOOL)isCheckReachability
//{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    //日期是否在明天
//    NSDate *VipTimeDate=[ZBCOMMETH changeStringToDate:AppProfile.userInfo.Expire];
//    BOOL isTomorrow = [calendar isDateInTomorrow:VipTimeDate];
//
//    if (!AppProfile.userInfo.IsVip ||(isTomorrow && AppProfile.userInfo.IsVip)) {
//        [self sendRequestHttpDataUrl:URL_Iap_Sync Dic:[NSDictionary dictionary] resMethod:JMP_HTTP_METHOD_POST isCheckReachability:isCheckReachability success:^(JMPHttpResponse *response, NSInteger resStatusCode, NSString *errorMessage) {
//            if (resStatusCode==0) {
//                [self getUserVIPInfo:isCheckReachability];
//            }
//        } failure:^(JMPHttpResponse *response, NSInteger resStatusCode, NSError *error) {
//        }];
//    }
//}
#pragma mark- 获取个人VIP信息
//-(void)getUserVIPInfo
//{
//    [self getUserVIPInfo:YES];
//}
//-(void)getUserVIPInfo:(BOOL)isCheckReachability
//{
//    NSString* identifierNumber = [ZBKeyChain getIDFV];
//    if (IsStringEmpty(identifierNumber)) return;
//    NSDictionary *dic =@{@"uuid":identifierNumber};
//    [self sendRequestHttpDataUrl:URL_Vip Dic:dic resMethod:JMP_HTTP_METHOD_POST isCheckReachability:isCheckReachability success:^(JMPHttpResponse *response, NSInteger resStatusCode, NSString *errorMessage) {
//        if (resStatusCode==0) {
//            NSDictionary *dic = response.rspData[@"data"];
//            AppProfile.userInfo = [ZBUserInfoModel mj_objectWithKeyValues:dic];
//            [AppProfile saveUserDefault:AppProfile.userInfo];
//        }else if (resStatusCode==10000 ||resStatusCode==10001)
//        {
//            [HTTPManager clearToken];//清除token
//            [AppProfile clearUserInfo:AppProfile.userInfo];//清除个人信息
//        }
//    } failure:^(JMPHttpResponse *response, NSInteger resStatusCode, NSError *error) {
//    }];
//}


@end
